package social.hub.oauth.scribe;

import org.scribe.builder.api.DefaultApi20;
import org.scribe.model.OAuthConfig;
import org.scribe.utils.Preconditions;

import social.hub.oauth.OAuthServiceConfig;
import social.hub.util.UrlBuilder;

public class GenericScribe20API extends DefaultApi20 {

	private final OAuthServiceConfig	serviceConfig;

	public GenericScribe20API(OAuthServiceConfig serviceConfig) {
		this.serviceConfig = serviceConfig;
	}

	@Override
	public String getAccessTokenEndpoint() {

		return buildUrl(serviceConfig.getAccessTokenUrl());

	}

	@Override
	public String getAuthorizationUrl(OAuthConfig config) {

		Preconditions.checkValidUrl(serviceConfig.getCallbackUrl(),
				"Must provide a valid url as callback. This service does not support OOB");

		return buildUrl(serviceConfig.getAuthorizeUrl());

	}

	private String buildUrl(String url) {

		UrlBuilder urlBuilder = new UrlBuilder(url);
		urlBuilder.addUrlParan("appId", serviceConfig.getAppId());
		urlBuilder.addUrlParan("apiKey", serviceConfig.getApiKey());
		urlBuilder.addUrlParan("apiSecret", serviceConfig.getApiSecret());
		urlBuilder.addUrlParan("callbackUrl", serviceConfig.getCallbackUrl());
		urlBuilder.addUrlParan("scope", serviceConfig.getScope());
		return urlBuilder.toString();

	}

}